<template>
  <div class="major-list">
    <a-card title="专业管理">
      <template #extra>
        <a-button type="primary" @click="showAddModal">添加专业</a-button>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="学院">
          <a-select 
            v-model:value="searchForm.college" 
            placeholder="请选择" 
            style="width: 200px" 
            allow-clear
            @change="handleSearch"
          >
            <a-select-option 
              v-for="college in colleges" 
              :key="college.id" 
              :value="college.id"
            >
              {{ college.college_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="showEditModal(record)">编辑</a>
              <a style="color: #ff4d4f" @click="handleDelete(record.id)">删除</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal 
      v-model:open="modalVisible" 
      :title="modalTitle" 
      @ok="handleSubmit" 
      @cancel="handleCancel"
    >
      <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="专业名称" required>
          <a-input v-model:value="formData.major_name" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="所属学院" required>
          <a-select v-model:value="formData.college" placeholder="请选择">
            <a-select-option 
              v-for="college in colleges" 
              :key="college.id" 
              :value="college.id"
            >
              {{ college.college_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { majorAPI, collegeAPI } from '@/api/system'
import type { Major, College } from '@/api/system'

const loading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('添加专业')
const currentRecord = ref<Major | null>(null)
const dataSource = ref<Major[]>([])
const colleges = ref<College[]>([])

const searchForm = reactive({
  college: undefined as number | undefined
})

const formData = ref({
  major_name: '',
  college: undefined as number | undefined
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '专业名称', dataIndex: 'major_name', key: 'major_name' },
  { title: '所属学院', dataIndex: 'college_name', key: 'college_name', width: 200 },
  { title: '操作', key: 'action', width: 150 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载学院列表
const loadColleges = async () => {
  try {
    const res = await collegeAPI.getList({ page_size: 1000 })
    colleges.value = res.data.results
  } catch (error: any) {
    message.error('加载学院列表失败: ' + (error.response?.data?.message || error.message))
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await majorAPI.getList({
      college: searchForm.college
    } as any)
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.college = undefined
  pagination.value.current = 1
  loadData()
}

// 显示添加弹窗
const showAddModal = () => {
  modalTitle.value = '添加专业'
  currentRecord.value = null
  formData.value = {
    major_name: '',
    college: undefined
  }
  modalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: Major) => {
  modalTitle.value = '编辑专业'
  currentRecord.value = record
  formData.value = {
    major_name: record.major_name,
    college: record.college
  }
  modalVisible.value = true
}

// 提交
const handleSubmit = async () => {
  if (!formData.value.major_name) {
    message.error('请输入专业名称')
    return
  }
  if (!formData.value.college) {
    message.error('请选择所属学院')
    return
  }

  try {
    if (currentRecord.value) {
      // 编辑
      await majorAPI.update(currentRecord.value.id, formData.value)
      message.success('更新成功')
    } else {
      // 新增
      await majorAPI.create(formData.value as any)
      message.success('添加成功')
    }
    modalVisible.value = false
    loadData()
  } catch (error: any) {
    message.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

// 取消
const handleCancel = () => {
  modalVisible.value = false
}

// 删除
const handleDelete = (id: number) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个专业吗？',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        await majorAPI.delete(id)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        message.error('删除失败: ' + (error.response?.data?.message || error.message))
      }
    }
  })
}

onMounted(() => {
  loadColleges()
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
